﻿using AVCUMPlatform.Entities;
using AVCUMPlatform.HelperLibrary;
using AVCUMPlatform.HelperLibrary.Cache;
using System;

namespace AVCUMPlatform.WXService.Model
{
    /// <summary>
    /// 微信js微信票据管理
    /// </summary>
    public class WXTicket
    {
        /// <summary>
        /// 实例
        /// </summary>
        private static WXTicket instance = new WXTicket();
        /// <summary>
        /// 锁
        /// </summary>
        private object sync_obj = new object();
        /// <summary>
        /// 微信应用id
        /// </summary>
        private string _appId { get; set; }
        /// <summary>
        /// 微信密钥
        /// </summary>
        private string _appSecret { get; set; }
        /// <summary>
        /// 缓存键
        /// </summary>
        public string cacheKey_Ticket = "WxCacheTicket";
        /// <summary>
        /// 缓存实例
        /// </summary>
        ICache cache = CacheFactory.GetCacheInstance();
        /// <summary>
        /// 缓存模型
        /// </summary>
        private CacheEntity cacheWxEntity = null;

        /// <summary>
        /// 私有构造
        /// </summary>
        private WXTicket()
        {
            if (cache.IsExists(cacheKey_Ticket))
            {
                cacheWxEntity = cache.Get<CacheEntity>(cacheKey_Ticket);
            }
        }

        /// <summary>
        /// 获取实例
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="appsecret"></param>
        /// <returns></returns>
        public static WXTicket GetInstance(string appid, string appsecret)
        {
            instance._appId = appid;
            instance._appSecret = appsecret;
            return instance;
        }

        /// <summary>
        /// js api 票据
        /// </summary>
        public string JSApiTicket
        {
            get
            {
                if (null == cacheWxEntity || DateTime.Now >= cacheWxEntity.ElapsedAt)
                {
                    lock (sync_obj)
                    {
                        if (null == cacheWxEntity || DateTime.Now >= cacheWxEntity.ElapsedAt)
                        {
                            DoGetTicket();
                        }
                    }
                }

                return cacheWxEntity.Content;
            }
        }

        /// <summary>
        /// 获取票据
        /// </summary>
        private void DoGetTicket()
        {
            if (cache.IsExists(cacheKey_Ticket))
            {
                cacheWxEntity = cache.Get<CacheEntity>(cacheKey_Ticket);
            }
            else
            {
                cacheWxEntity = new CacheEntity() { ElapsedAt = DateTime.Now, UpdateTime = DateTime.Now };
            }

            if (DateTime.Now >= cacheWxEntity.ElapsedAt)
            {
                var ticket = HTTPHelper.Post<TicketEntity>(
                    string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi",
                    WXToken.GetInstance(_appId, _appSecret).AccessToken), string.Empty);

                if (ticket.Expires_in > 0)
                {
                    //这里为了解决边界问题，将默认时间7200秒缩短一下，给个5分钟的过渡时间
                    int expireSeconds = ticket.Expires_in - 300;
                    cacheWxEntity.ElapsedAt = DateTime.Now.AddSeconds(expireSeconds);
                    cacheWxEntity.Content = ticket.Ticket;
                    cacheWxEntity.UpdateTime = DateTime.Now;
                    cache.Remove(cacheKey_Ticket);
                    cache.Set(cacheKey_Ticket, cacheWxEntity, TimeSpan.FromSeconds(expireSeconds));
                }
            }
        }
    }
}
